package com.gem.netty.message;

import com.gem.enums.MessageColorType;
import com.gem.factory.game.GameFactory;
import com.gem.factory.room.RoomFactory;
import com.gem.factory.user.UserFactory;
import com.gem.netty.entity.ClientContent;
import com.gem.netty.session.GroupSession;
import com.gem.netty.session.GroupSessionFactory;
import com.gem.utils.R;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;

/**
 * Author: Xhy
 * CreateTime: 2022-09-21 15:46
 * 加入房间
 */
public class JoinRoomMessage implements Message {

    @Override
    public void handler(ClientContent content) {
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        String roomId = content.getRoomId();
        String userId = content.getSendId();
        R r = RoomFactory.join(roomId, userId);
        if (!r.getState()){
            content.getCtx().writeAndFlush(new TextWebSocketFrame(r.type(content.getType()).toString()));
            return;
        }
        groupSession.joinMember(roomId,userId);
        // 给房间发送消息
        List<Channel> members = groupSession.getMembersChannel(roomId);
        GameFactory.notifyUsers(members,R.ok().data("color", MessageColorType.SYSTEM_MESSAGE.type)
                .data("data", RoomFactory.get(roomId).getState()).message(UserFactory.get(userId) + "加入房间").type(content.getType()),roomId);
    }
}
